package edu.unsw.comp9321.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import edu.unsw.comp9321.common.ServiceLocatorException;

public class CustomerTypeDAOImpl implements CustomerTypeDAO {

	private Connection connection;

	public CustomerTypeDAOImpl() throws ServiceLocatorException, SQLException {
		connection = DBConnectionFactory.getConnection();
	}

	@Override
	public List<CustomerTypeDTO> findAll() {
		List<CustomerTypeDTO> list = new ArrayList<CustomerTypeDTO>();
		try {
			Statement stmnt = connection.createStatement();
			String query = "SELECT * FROM customer_type";
			ResultSet res = stmnt.executeQuery(query);
			while (res.next()) {
				int customerTypeId = res.getInt("customer_type_id");
				int ageMin = res.getInt("age_min");
				int ageMax = res.getInt("age_max");
				int licenseDurMin = res.getInt("license_dur_max");
				int licenseDurMax = res.getInt("license_dur_min");
				float insuranceExcess = res.getFloat("insurance_excess");
				list.add(new CustomerTypeDTO(customerTypeId, ageMin, ageMax, licenseDurMax, licenseDurMin, insuranceExcess));
			}
			res.close();
			stmnt.close();
		} catch (Exception e) {
			System.out.println("Caught Exception");
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public CustomerTypeDTO findCustomerType(int age, int licenseDuration) {
		CustomerTypeDTO customerType = null;
		try {
			String query = "SELECT * FROM customer_type " +
					"WHERE age_min <= ? AND age_max >= ? " +
					"AND license_dur_min <= ? AND license_dur_max >= ?;";
			PreparedStatement stmnt = connection.prepareStatement(query);
			stmnt.setInt(1, age);
			stmnt.setInt(2, age);
			stmnt.setInt(3, licenseDuration);
			stmnt.setInt(4, licenseDuration);
			ResultSet res = stmnt.executeQuery();
			while (res.next()) {
				int customerTypeId = res.getInt("customer_type_id");
				int ageMin = res.getInt("age_min");
				int ageMax = res.getInt("age_max");
				int licenseDurMax = res.getInt("license_dur_max");
				int licenseDurMin = res.getInt("license_dur_min");
				float insuranceExcess = res.getFloat("insurance_excess");
				customerType = new CustomerTypeDTO(customerTypeId, ageMin, ageMax, licenseDurMax, licenseDurMin, insuranceExcess); 
			}
			res.close();
			stmnt.close();
		} catch (Exception e) {
			System.out.println("Caught Exception");
			e.printStackTrace();
		}
		return customerType;
	}

}
